import json
import os
import socket
import threading
import chessman
import image
import pygame
from pygame.locals import *
import sys

def resource_path(relative_path):
    """获取打包后资源的绝对路径"""
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

def my_client(c: socket.socket, is_white):
    global can
    global finish
    global begin
    global rival
    global me
    while True:
        recv = c.recv(1024)
        if recv:
            # print(recv)
            loads = json.loads(recv)

            type = loads["type"]
            if type == -1:
                err = loads["err"]
                print(f"{err}")
            elif type == 0:
                zb = loads["zb"]
                color = loads["color"]
                if color == my_color:
                    can = False
                else:
                    can = True
                chessman_img = chessman.Chessman(resource_path(f"pic/{color}.png"), (list_x[zb[0]] - 32, list_y[zb[1]] - 32),
                                                 (64, 64))
                chessman_img.update()
                chessman_img.draw(DISPLAYSURF)
                pygame.display.update()
            elif type == 1:
                result= loads["result"]
                if result=="win":
                    win_img.update()
                    win_img.draw(DISPLAYSURF)
                    pygame.display.update()
                    print("您赢了")
                else:
                    lose_img.update()
                    lose_img.draw(DISPLAYSURF)
                    pygame.display.update()
                    print("您输了")
            elif type == 2:
                rival = True
            elif type == 3:
                me = loads['me']
                print(f"当前房间号:{me}")
            elif type == 4:
                pass

win_img = image.Image( resource_path("pic/win.png"), (0, 200), (800, 400))
lose_img = image.Image(resource_path("pic/lose.png"), (0, 200), (800, 400))
list_x = [65, 115, 167, 217, 268, 319, 371, 420, 472, 523, 574, 626, 677, 729, 780]
list_y = [14, 64, 116, 167, 217, 269, 319, 373, 425, 474, 527, 578, 628, 681, 731]



def find_closest_value(target, lst):
    min_diff = float('inf')
    index = None

    for i, val in enumerate(lst):
        diff = abs(target - val)
        if diff < min_diff:
            min_diff = diff
            # closest_value = val
            index = i
    return index


# ==========================================# ==========================================# ==========================================
# 当前是否可以下
can = True
# 游戏是否结束
finish = False
begin = False
me = False
rival = None

c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_ip = input("请输入服务器ip:")
# server_ip = '127.0.0.1'
c.connect((server_ip, 40001))
threading.Thread(target=my_client, args=(c, None)).start()
client_msg = {
    "type": 3
}
c.send(json.dumps(client_msg).encode())
# input_color = input("请选择棋子颜色:(1黑2白)")
# if input_color == '1':
#     my_color = "black"
# else:
#     my_color = "white"
my_color = None
input_room_id = input("请输入房间号:(有就输入没有就回车)")
if input_room_id:
    # 加入房间
    client_msg = {
        "type": 2,
        "other": input_room_id,
        "me": me
    }
    c.send(json.dumps(client_msg).encode())
    my_color = "white"
else:
    my_color = "black"

pygame.init()
# 设置棋盘大小
DISPLAYSURF = pygame.display.set_mode((800, 800))
# 设置背景颜色
DISPLAYSURF.fill((255, 255, 255))
# 加载图片对象
img_board = pygame.image.load(resource_path("pic/board.png"))
DISPLAYSURF.blit(img_board, (0, 0))
pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if not rival:
                continue
            if finish:
                continue
            if event.button != 1:
                continue
            if not can:
                continue
            x, y = pygame.mouse.get_pos()
            xx = find_closest_value(x, list_x)
            yy = find_closest_value(y, list_y)

            # 坐标
            zb = (xx, yy)
            client_msg = {
                "type": 0,
                "color": my_color,
                "zb": zb,
                "other":input_room_id
            }

            i = c.send(json.dumps(client_msg).encode())
